package example;

import java.net.InetAddress;
import java.sql.Date;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class Utils {
	
	public static final int D_M_Y_FORMAT = 0;
	public static final int Y_M_D_FORMAT = 1;
	
	public static final String SQL_DATE_DELIMETER = "-";
	
	
	public static Date formatDate( String date, int format ) {
		
		//Esplodo la stringa
		String[] t;
		Date ret = null;
		
		t = date.split( "/" );
		
		switch ( format ) {
			case D_M_Y_FORMAT:
				ret =  java.sql.Date.valueOf( t[2] + SQL_DATE_DELIMETER + t[1] + SQL_DATE_DELIMETER + t[0]  );
				break;
			case Y_M_D_FORMAT:
				ret =  java.sql.Date.valueOf( t[0] + SQL_DATE_DELIMETER + t[1] + SQL_DATE_DELIMETER + t[2]  );
				break;
			default: {}
		}
		
		return ret;
	}
	
	public static boolean checkEmail(String email){  
		boolean isValid = false;
		 String expression = "^[\\w\\.-]+@([\\w\\-]+\\.)+[A-Z]{2,4}$";  
		 CharSequence inputStr = email;  
		 //Make the comparison case-insensitive.  
		 Pattern pattern = Pattern.compile(expression,Pattern.CASE_INSENSITIVE);  
		 Matcher matcher = pattern.matcher(inputStr);  
		 
		 if( matcher.matches() ){  
			 isValid = true;  
		 }  
		 return isValid;  
	} 


	
	public static Result checkCF(String cf) {
		Result result;
	    int i, s, c;
	    String cf2;
	    int setdisp[] = {1, 0, 5, 7, 9, 13, 15, 17, 19, 21, 2, 4, 18, 20,
	        11, 3, 6, 8, 12, 14, 16, 10, 22, 25, 24, 23 };
	    
	    if( cf.length() != 16 )
	        return new Result(false, null, "La lunghezza del codice fiscale non e' "
	        + "corretta: il codice fiscale dovrebbe essere lungo "
	        + "esattamente 16 caratteri.");
	    cf2 = cf.toUpperCase();
	    for( i=0; i<16; i++ ){
	        c = cf2.charAt(i);
	        if( ! ( c>='0' && c<='9' || c>='A' && c<='Z' ) )
	            return new Result( false, null, "Il codice fiscale contiene dei caratteri non validi: "
	            + "i soli caratteri validi sono le lettere e le cifre.");
	    }
	    s = 0;
	    for( i=1; i<=13; i+=2 ){
	        c = cf2.charAt(i);
	        if( c>='0' && c<='9' )
	            s = s + c - '0';
	        else
	            s = s + c - 'A';
	    }
	    for( i=0; i<=14; i+=2 ){
	        c = cf2.charAt(i);
	        if( c>='0' && c<='9' )     c = c - '0' + 'A';
	        s = s + setdisp[c - 'A'];
	    }
	    if( s%26 + 'A' != cf2.charAt(15) )
	        return new Result(false, null, "Il codice fiscale non e' corretto: "
	        + "il codice di controllo non corrisponde.");
	    return new Result( true, null, "");
	}


}
